import datetime
import time
import logging

import requests

from config import Config

LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='song.log', level=logging.INFO, format=LOG_FORMAT)


def login():
    try:
        page = requests.get(Config.LOGIN_PAGE)
        eai_sess = page.headers['Set-Cookie'].split(';')[0]

        data = 'username=' + Config.USERNAME + '&password=' + Config.PASSWORD
        Config.LOGIN_HEADER['Cookie'] = eai_sess
        resp = requests.post(Config.LOGIN_URL, data=data, headers=Config.LOGIN_HEADER)
        if resp.json()['m'] == Config.REPORT_SUCCESS:
            return eai_sess
        else:
            return None
    except ConnectionError as e:
        logging.error('连接失败')
        raise e
    except SyntaxError as e:
        logging.error('json格式错误')
        raise e


def report():
    try:
        date = time.strftime("%Y%m%d", time.localtime())
        Config.PAYLOAD['date'] = date
        cookies = login()
        Config.REPORT_HEADER['Cookie'] = cookies
        resp = requests.post(url=Config.REPORT_URL, headers=Config.REPORT_HEADER, data=Config.PAYLOAD)

        msg = resp.json()['m']
        if msg == Config.REPORT_SUCCESS:
            return True
        elif msg == Config.REPORT_ALREADY:
            return True
        else:
            return False

    except ConnectionError as e:
        logging.error('连接失败')
        raise e
    except SyntaxError as e:
        logging.error('json格式错误')
        raise e


if __name__ == '__main__':

    while True:
        cur = datetime.datetime.now().hour
        if cur == Config.REPORT_HOUR:
            retry = 0
            r = report()
            while r is False:
                retry += 1
                r = report()

                if retry == 10:
                    break

            if r is False:
                logging.error('打卡失败，尝试了{}次'.format(retry))
            else:
                logging.info('打卡成功')
        time.sleep(3600)
